//*************************************
// 不读，一直写，写端阻塞
// ************************************
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main()
{
  int pipefd[2] = {0};
  if(pipe(pipefd) < 0){
    perror("pipe");
    return 1;
  }
 
  pid_t id = fork();
  if(0 == id){//child, write
    close(pipefd[0]);//close  read 
    const char * msg = "I am child ...";
    while(1){
        write(pipefd[1], msg, strlen(msg));//msg -> pipefd[1],注意strlen不要写入\n，只写有效内容
        sleep(1);
    }
    close(pipefd[1]);
    exit(0);
  }
  else{//parent, read 
    close(pipefd[1]);//close write 
    close(pipefd[0]);//关闭读
    char buffer[64];
    while(1){
      ssize_t s = read(pipefd[0], buffer, sizeof(buffer)-1);//pipefd[0]读到buffer 第三个参数表示期望读取多少字节
      if(s > 0){
        buffer[s] = '\0';//buffer[s] = 0;最后一个结尾处为字符串结束
        printf("father get Message: %s\n", buffer);
      }
      else if(s == 0){
        printf("read file end\n");
        break;
      }
      else{
        printf("read error\n");
        break;
      }
      //close(pipefd[0]);//read一次后，关闭读端
      //break;
    }
    sleep(3);
    //int status = 0;
    //waitpid(id, &status, 0);//阻塞式等待
    //printf("child quit!, sig: %d\n", status & 0x7F);

  }//end of parent
  return 0;
}
